package zhtt.scheduler;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhtt.entity.Expression;
import zhtt.service.SyncDataService;

import java.util.Date;
import java.util.Iterator;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * Created by zhtt on 2016/10/28.
 */
@Service
public class ZhttScheduler {

    @Autowired
    private SyncDataService syncDataService;

    public void init(Date startDate,Expression expression) throws SchedulerException{
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobDetail jobDetail = newJob(ZhttJob.class).withIdentity("job1", "group1").build();
        jobDetail.getJobDataMap().put("syncDataService", syncDataService);
        jobDetail.getJobDataMap().put("expression", expression);
        CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1")
                .withSchedule(cronSchedule(expression.getExpression())).build();
        scheduler.scheduleJob(jobDetail, trigger);
        if(expression.isStartState()){
            scheduler.start();
        }
    }

    public void reStart(Date startDate,Expression expression) throws SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Iterator<Scheduler> schedIterator=schedulerFactory.getAllSchedulers().iterator();
        while(schedIterator.hasNext()){
            Scheduler scheduler=(Scheduler)schedIterator.next();
            if(scheduler!=null){
                scheduler.shutdown(true);
            }
        }
        this.init(startDate, expression);
    }

    public void stop() throws SchedulerException{
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Iterator<Scheduler> schedIterator=schedulerFactory.getAllSchedulers().iterator();
        while(schedIterator.hasNext()){
            Scheduler scheduler=(Scheduler)schedIterator.next();
            if(scheduler!=null){
                scheduler.shutdown(true);
            }
        }
    }

    public boolean isStarted() throws SchedulerException{
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Iterator<Scheduler> schedIterator=schedulerFactory.getAllSchedulers().iterator();
        while(schedIterator.hasNext()){
            Scheduler scheduler=(Scheduler)schedIterator.next();
            if(scheduler!=null){
                return scheduler.isStarted();
            }
        }
        return false;
    }
}
